package com.ho1ho.springboot.framework.core.utils;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

public class RequestUtil {
	private static final String UNKNOWN = "unknown";
	private static final String X_REQUESTED_WITH = "X-Requested-With";
	private static final String XML_HTTP_REQUEST = "XMLHttpRequest";
	private static final String[] REAL_REMOTE_ADDR_NAMES = new String[] { "X-Forwarded-For", "Proxy-Client-IP",
			"WL-Proxy-Client-IP" };

	private RequestUtil() {
	}

	public static String getIpAddress(HttpServletRequest req) {
		if (req == null) {
			return null;
		}
		String ip;
		for (String realRemoteAddrName : REAL_REMOTE_ADDR_NAMES) {
			ip = req.getHeader(realRemoteAddrName);
			if (!StringUtils.isBlank(ip) && !UNKNOWN.equalsIgnoreCase(ip)) {
				final int idx = ip.indexOf(',');
				if (-1 < idx) {
					ip = ip.substring(0, idx);
				}
				return ip.trim();
			}
		}
		return req.getRemoteAddr();
	}

	public static boolean isAjaxRequest(HttpServletRequest req) {
		return XML_HTTP_REQUEST.equals(req.getHeader(X_REQUESTED_WITH));
	}

	public static String getBaseUrl(HttpServletRequest req) {
		RedirectUrlBuilder urlBuilder = new RedirectUrlBuilder();
		urlBuilder.setScheme(StringUtils.isBlank(req.getHeader("X-Forwarded-Proto")) ? req.getScheme()
				: req.getHeader("X-Forwarded-Proto"));
		urlBuilder.setServerName(StringUtils.isBlank(req.getHeader("X-Forwarded-Host")) ? req.getServerName()
				: req.getHeader("X-Forwarded-Host"));
		urlBuilder.setPort(StringUtils.isBlank(req.getHeader("X-Forwarded-Port")) ? req.getServerPort()
				: Integer.parseInt(req.getHeader("X-Forwarded-Port")));
		urlBuilder.setContextPath(req.getContextPath());
		return urlBuilder.getUrl();
	}
}
